package com.pointmi.transactiondao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class TransactionDAOImpl implements TransactionDAO {
	
	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	protected final Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
	
	public void saveOrUpdate(Transaction transaction) {
		getCurrentSession().saveOrUpdate(transaction);
	}

	@SuppressWarnings("unchecked")
	public List<Transaction> findAllTransaction() {
			Query query = getCurrentSession().createQuery("from transaction");
			return (List<Transaction>) query.list();
	}
	
	@SuppressWarnings("rawtypes")
	private Transaction foundTransaction(List list) {
		Transaction transaction = null;
		if (list.size() > 0) {
			transaction = (Transaction) list.get(0);
		}
		return transaction;
	}
	
	public Transaction findTransactionByCustomerId(String customerId)
	{
		Query query = getCurrentSession().createQuery(
				"from transaction where customerId = :customerId");
		query.setParameter("customerId", customerId);
		@SuppressWarnings("rawtypes")
		List list = query.list();
		return foundTransaction(list);
	}
}
